package com.tang.boot.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tang.boot.boot.dao.BookDao;
import com.tang.boot.boot.domain.Book;
import com.tang.boot.boot.exception.BusinessException;
import com.tang.boot.boot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.sun.tools.classfile.Attribute.Code;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;

    @Override
    public Boolean insert(Book book) {
        return bookDao.insert(book) > 0;
    }

    @Override
    public Boolean delete(Integer id) {
        return bookDao.deleteById(id) > 0;
    }

    @Override
    public Boolean update(Book book) {
        return bookDao.updateById(book) > 0;
    }

    @Override
    public Book getById(Integer id) {
        if (id == 1){
            throw new BusinessException(Code.BUSINESS_ERR, "请不要使用你的技术挑战我的耐心");
        }
        Book book = bookDao.selectById(id);
        return book;
    }

    @Override
    public List<Book> getAll() {
        List<Book> list = bookDao.selectList(null);
        return list;
    }

    @Override
    public IPage<Book> getPage(int currentPage, int pageSize) {
        IPage page = new Page(currentPage, pageSize);
        bookDao.selectPage(page, null);
        return page;
    }

    @Override
    public IPage<Book> getPage(int currentPage, int pageSize, Book book) {
        LambdaQueryWrapper<Book> lambdaQueryWrapper = new LambdaQueryWrapper<Book>();
        lambdaQueryWrapper.like(!book.getName().isEmpty(), Book::getName, book.getName());
        lambdaQueryWrapper.like(!book.getType().isEmpty(), Book::getType, book.getType());
        IPage page = new Page(currentPage, pageSize);
        bookDao.selectPage(page, lambdaQueryWrapper);
        return page;
    }
}
